package com.gao.demo02;

/**
 * 生产者消费者
 * 线程之间的通信问题
 * 线程交替执行 A B 操作同一个变量 num = 0
 * A num + 1
 * B num - 1
 */
public class demo01 {
    public static void main(String[] args) {
        Resource resource = new Resource();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.decrease();
                } catch (InterruptedException e) {

                }
            }
        },"C").start();new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.decrease();
                } catch (InterruptedException e) {

                }
            }
        },"D").start();
    }
}

//判断等待 -> 业务 -> 通知 生产者消费者模式
class Resource{
    private int number = 0;

    public synchronized void increase() throws InterruptedException {
        while (number != 0){
//            等待
            this.wait();
        }
//        业务
        number++;
        System.out.println(Thread.currentThread().getName() + " -> " + number);
//        通知其他线程，我+1完毕
        this.notifyAll();
    }

    public synchronized void decrease() throws InterruptedException {
        while(number == 0){
//            等待
            this.wait();
        }
//        业务
        number--;
        System.out.println(Thread.currentThread().getName() + " -> " + number);
//        通知其他线程，我-1完毕
        this.notifyAll();
    }

}
